package cn.edu.ujs.coor.common.interceptor;

import cn.edu.ujs.coor.common.exception.CoorException;
import cn.edu.ujs.coor.util.JwtUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Map;

/**
 * 认证拦截器
 *
 * @author 柳曾雄
 * @date 2018-07-30
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 忽略OPTIONS请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            throw new CoorException("er_000001", "尚未登录");
        }
        Map<String, String> info = JwtUnit.decode(token);
        if (info == null || info.size() == 0) {
            throw new CoorException("er_000001", "登录信息异常, 请重新登录");
        }
        Long current = Calendar.getInstance().getTimeInMillis();
        if (Long.parseLong(info.get("expire")) < current) {
            throw new CoorException("er_000001", "登录信息已过期，请重新登录");
        }
        return true;
    }
}
